﻿#include "CMouse.h"

CMouse::CMouse(HINSTANCE hIns,HWND hwnd) {
	this->hWnd = hwnd;
	this->hInstance = hIns;
	this->di8 = 0;
	this->did8 = 0;
}

CMouse::~CMouse(void) {

}

bool CMouse::Init() {
	HRESULT hr = DirectInput8Create(
		this->hInstance, // hInstance của chương trình
		DIRECTINPUT_VERSION, // tham số mặc định
		IID_IDirectInput8, // tham số mặc định
		(void**)&this->di8, // con trỏ nhận dữ liệu trả về
		NULL // tham số dùng thêm
		);
	if(FAILED(hr)) {
		return false;
	}
	// tạo bàn phím. GUID_SysKeyboard là chỉ bàn phím.
	hr = this->di8->CreateDevice(GUID_SysMouse,&this->did8,NULL);
	if(FAILED(hr)) {
		return false;
	}
	// dạng dữ liệu sẽ được nhận
	hr = this->did8->SetDataFormat(&c_dfDIMouse2);
	if(FAILED(hr)) {
		return false;
	}
	// loại hoạt động. DISCL_FOREGROUND nghĩa là chỉ hoạt động khi cửa sổ hwnd đang được handle
	hr = this->did8->SetCooperativeLevel(this->hWnd,DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	if(FAILED(hr)) {
		return false;
	}
	// yêu cầu thiết bị
	hr = this->did8->Acquire();
	if(FAILED(hr)) {
		return false;
	}
	return true;
}

void CMouse::GetState() {
	// lấy trạng thái thiết bị chuột
	HRESULT hr = this->did8->GetDeviceState(sizeof(DIMOUSESTATE2),&mouseState);
	if(FAILED(hr)) {
		// Device has probably been lost if failed, so keep
		//  trying to get it until it's found
		do
		{
			hr = this->did8->Acquire();
		}while( hr == DIERR_INPUTLOST );
		// If we failed for some other reason, quit the method
		if(FAILED(hr))
			return;
		// Read the device state again
		this->did8->GetDeviceState( sizeof(DIMOUSESTATE2),&mouseState);
	}
}

void CMouse::Shutdown() {
	if(this->di8) {
		this->di8->Release();
		this->di8 = NULL;
	}
	if(this->did8) {
		this->did8->Release();
		this->did8 = NULL;
	}
}

bool CMouse::CheckMouseButtons(short buttonNumber) {
	// Check to see if mouse button was hit
	//  0 = Left Button
	//  1 = Right Button
	//  3 = Middle Button (Scroll Wheel pressed)
	//  4-7 = Side buttons
	if( mouseState.rgbButtons[buttonNumber] & 0x80 )
	{
		// mouse button was pressed
		return true;
	}
	else
	{
		// mouse button was not pressed
		return false;
	}
}

int CMouse::CheckMouseMoveX() {
	// return relative changes
	// you probably want to scale your 1X
	// value so it is not so drastic in your application
	return mouseState.lX;
}

int CMouse::CheckMouseMoveY() {
	// return relative changes
	// you probably want to scale your 1Y
	// value so it is not so drastic in your application
	return mouseState.lY;
}

int CMouse::CheckMouseScroll() {
	// return relative changes
	// you probably want to scale your 1Z
	// value so it is not so drastic in your application
	return mouseState.lZ;
}
